package com.freemyleft.left.zapp.net.download;

/**
 * Created by FreeMyleft on 2017/12/3.
 */

import android.os.AsyncTask;

import com.freemyleft.left.zapp.net.RestCreator;
import com.freemyleft.left.zapp.net.callback.IError;
import com.freemyleft.left.zapp.net.callback.IFailure;
import com.freemyleft.left.zapp.net.callback.IRequest;
import com.freemyleft.left.zapp.net.callback.ISuccess;

import java.util.WeakHashMap;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 下载管理类
 */
public class DownloadHandler {
    private final String URL;
    private WeakHashMap<String, Object> PARAMS;
    private final ISuccess SUCCESS;
    private final IFailure FAILURE;
    private final IRequest REQUEST;
    private final IError ERROR;
    private final String DOWNLOAD_DIR;//下载的目录
    private final String EXTENSION;//后缀名
    private final String NAME;//文件名

    public DownloadHandler(String url, ISuccess success, IFailure failure,
                           IRequest request, IError error, String downloadDir, String extension, String name) {
        this.URL = url;
        this.SUCCESS = success;
        this.FAILURE = failure;
        this.REQUEST = request;
        this.ERROR = error;
        this.DOWNLOAD_DIR = downloadDir;
        this.EXTENSION = extension;
        this.NAME = name;
    }


    /**
     * 处理Download
     */
    public final void handleDownload(){
        if (REQUEST!=null){
            // TODO: 2017/12/3 开始下载了
            REQUEST.onRequestStart();
        }
        RestCreator.getRestService().download(URL,PARAMS).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
               if (response.isSuccessful()){
                   final ResponseBody responseBody=response.body();
                   final SaveFileTask task=new SaveFileTask(REQUEST,SUCCESS);
                   task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,DOWNLOAD_DIR,EXTENSION,responseBody);
                   if (task.isCancelled()){
                       if (REQUEST!=null){
                           REQUEST.onRequestEnd();
                       }
                   }else {
                       if (ERROR!=null){
                           ERROR.onError(response.code(),response.message());
                       }
                   }

               }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                if (FAILURE!=null){
                    FAILURE.onFailure();
                }

            }
        });

    }
}
